"""
Gemini视频分类器

基于Google Gemini API的视频内容分类器。
"""

import time
from typing import Dict, List, Any
from datetime import datetime
import logging

from src.core.di import Injectable, Inject
from src.modules.scanners.base import FileInfo, FileType, FileCategory
from src.services.gemini_service import GeminiService
from .base import AIClassifier, ClassificationResult


@Injectable(scope="singleton")
class GeminiVideoClassifier(AIClassifier):
    """
    Gemini视频分类器
    
    使用Google Gemini API进行视频内容分析和分类。
    """
    
    def __init__(self,
                 gemini_service: GeminiService = Inject(GeminiService),
                 config: Dict[str, Any] = Inject("config"),
                 logger: logging.Logger = Inject("logger")):
        self.gemini_service = gemini_service
        self.config = config
        self.logger = logger
        
        # AI分类器配置
        self.ai_config = config.get("ai_classifier", {})
        self.confidence_threshold = self.ai_config.get("confidence_threshold", 0.7)
        self.max_frames = self.ai_config.get("max_frames_per_video", 5)
    
    @property
    def name(self) -> str:
        return "gemini_video_classifier"
    
    @property
    def version(self) -> str:
        return "1.0.0"
    
    @property
    def supported_file_types(self) -> List[str]:
        return ["video", "mp4", "avi", "mov", "mkv", "webm"]
    
    def is_available(self) -> bool:
        """检查分类器是否可用"""
        return self.gemini_service.is_available()
    
    async def classify(self, file_info: FileInfo, **kwargs) -> ClassificationResult:
        """分类视频文件"""
        start_time = time.time()
        
        # 检查文件类型
        if file_info.file_type != FileType.VIDEO:
            return ClassificationResult(
                success=False,
                error=f"不支持的文件类型: {file_info.file_type.value}",
                classifier_type=self.name,
                timestamp=datetime.now()
            )
        
        # 检查服务可用性
        if not self.is_available():
            return ClassificationResult(
                success=False,
                error="Gemini服务不可用",
                classifier_type=self.name,
                timestamp=datetime.now()
            )
        
        try:
            self.logger.info(f"使用Gemini分析视频: {file_info.name}")
            
            # 调用Gemini服务分析视频
            analysis_result = await self.gemini_service.analyze_video_content(
                file_info.path,
                max_frames=kwargs.get("max_frames", self.max_frames)
            )
            
            processing_time = time.time() - start_time
            
            if not analysis_result.get("success", False):
                return ClassificationResult(
                    success=False,
                    error=analysis_result.get("error", "AI分析失败"),
                    classifier_type=self.name,
                    processing_time=processing_time,
                    timestamp=datetime.now()
                )
            
            # 解析分类结果
            category_str = analysis_result.get("category", "unclassified")
            confidence = analysis_result.get("confidence", 0.0)
            reasoning = analysis_result.get("reasoning", "")
            features = analysis_result.get("features", [])
            
            # 转换分类字符串为枚举
            try:
                category = FileCategory(category_str)
            except ValueError:
                self.logger.warning(f"未知的分类类型: {category_str}")
                category = FileCategory.UNCLASSIFIED
            
            # 创建分类结果
            result = ClassificationResult(
                category=category,
                confidence=confidence,
                reasoning=reasoning,
                features=features,
                classifier_type=self.name,
                model_name=self.gemini_service.model_name,
                processing_time=processing_time,
                timestamp=datetime.now(),
                raw_response=analysis_result.get("raw_response", ""),
                metadata={
                    "frames_analyzed": analysis_result.get("frames_analyzed", 0),
                    "gemini_model": self.gemini_service.model_name,
                    "api_version": "v1"
                },
                success=True
            )
            
            self.logger.info(
                f"Gemini分类完成: {file_info.name} -> {category.value} "
                f"(置信度: {confidence:.2f}, 耗时: {processing_time:.2f}s)"
            )
            
            return result
            
        except Exception as e:
            processing_time = time.time() - start_time
            error_msg = f"Gemini分类失败: {e}"
            self.logger.error(error_msg)
            
            return ClassificationResult(
                success=False,
                error=error_msg,
                classifier_type=self.name,
                processing_time=processing_time,
                timestamp=datetime.now()
            )
    
    async def classify_with_fallback(self, file_info: FileInfo, fallback_classifier=None, **kwargs) -> ClassificationResult:
        """
        带回退机制的分类
        
        如果Gemini分类失败或置信度过低，使用回退分类器。
        """
        # 首先尝试Gemini分类
        result = await self.classify(file_info, **kwargs)
        
        # 检查是否需要回退
        need_fallback = (
            not result.success or 
            result.confidence < self.confidence_threshold
        )
        
        if need_fallback and fallback_classifier:
            self.logger.info(f"Gemini分类置信度过低或失败，使用回退分类器: {file_info.name}")
            
            try:
                fallback_result = await fallback_classifier.classify(file_info, **kwargs)
                
                if fallback_result.success:
                    # 合并结果，保留Gemini的分析信息
                    fallback_result.metadata.update({
                        "gemini_result": result.to_dict(),
                        "fallback_used": True,
                        "fallback_reason": "低置信度" if result.success else "分类失败"
                    })
                    
                    return fallback_result
                    
            except Exception as e:
                self.logger.error(f"回退分类器也失败了: {e}")
        
        return result
    
    def get_classification_statistics(self) -> Dict[str, Any]:
        """获取分类统计信息"""
        # 这里可以添加统计信息收集逻辑
        return {
            "total_classifications": 0,
            "successful_classifications": 0,
            "average_confidence": 0.0,
            "average_processing_time": 0.0,
            "category_distribution": {},
            "error_rate": 0.0
        }
    
    async def validate_classification(self, file_info: FileInfo, expected_category: FileCategory) -> Dict[str, Any]:
        """
        验证分类结果
        
        用于测试和评估分类器性能。
        """
        result = await self.classify(file_info)
        
        if not result.success:
            return {
                "success": False,
                "error": result.error
            }
        
        is_correct = result.category == expected_category
        
        return {
            "success": True,
            "is_correct": is_correct,
            "predicted_category": result.category.value,
            "expected_category": expected_category.value,
            "confidence": result.confidence,
            "processing_time": result.processing_time
        }
